import { apiGetClassifyWallList, type ClassifyWallList } from '@/api/classify';
import { useEffect, useRef, useState } from 'react';
import styles from './styles.module.scss';
import { useAppSelector } from '@/hooks/useStore';
import { LazyImage } from './LazyImage';

export default function Overview() {
  const { randomWall } = useAppSelector(state => state.user);
  const [data, setData] = useState<ClassifyWallList[]>([]);
  const [pageNum, setPageNum] = useState(1);
  const [loading, setLoading] = useState(false);

  const handleScroll = e => {
    const container = e.target;
    if (container.scrollTop + container.offsetHeight > container.scrollHeight - 10 && !loading) {
      setLoading(true);
      setPageNum(pageNum + 1);
      getImage();
    }
    // 在这里添加你的逻辑，例如判断是否滚动到右侧边缘
  };
  const getImage = async () => {
    const imgDatas: ClassifyWallList[] = [];
    let num = pageNum;
    for (let i = 0; i < 2; i++) {
      num += i;
      const imgData = await apiGetClassifyWallList({ pageNum: num, classid: randomWall[0].classid });
      imgDatas.push(
        ...imgData.data.map(item => ({
          ...item,
          picurl: item.smallPicurl.replace('_small.webp', '.jpg'),
        }))
      );
    }
    setData([...data, ...imgDatas]);
    setPageNum(num);
    setLoading(false);
  };
  useEffect(() => {
    if (!randomWall.length) {
      return;
    }
    console.log('randomWall', randomWall);
    // 获取数据
    getImage();
  }, [randomWall]);
  console.log(data);

  return (
    <div className={`${styles.imgList} imgList`} onScroll={handleScroll}>
      {data.map(item => {
        return <LazyImage key={item._id} className={styles.img} src={item.picurl} alt='' />;
      })}
    </div>
  );
}
